﻿using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;

public class LightDataHelper
{
    private string path = Application.dataPath + "/StreamingAssets/LightInfo"; 
    public static string lightFile = "LightData.json";

    private static LightDataHelper instances;

    public static LightDataHelper Instances
    {
        get
        {
            if (instances == null)
            {
                instances = new LightDataHelper();
            }
            return instances;
        }
    }

    public List<LightData> lightDataList;

    public LightDataHelper()
    {
        lightDataList = new List<LightData>();

    }

    /// <summary>
    /// 保存灯光数据
    /// </summary>
    /// <param name="lightData"></param>
    public void SaveLightData(string lightData)
    {
        lightDataList.Add(new LightData(lightData));
        SaveDate(lightFile);
    }

    /// <summary>
    /// 保存本地数据
    /// </summary>
    private void SaveDate(string file)
    {
        //判断路径和文件是否存在
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        string fileName = Path.Combine(path, file);
        if (!File.Exists(fileName))
        {
            FileStream fs = File.Create(fileName);
            fs.Close();
        }

        //保存数据到指定路径文件
        string json = JsonUtility.ToJson(LightDataHelper.Instances);
        File.WriteAllText(fileName, json, Encoding.UTF8);
    }

    /// <summary>
    /// 加载本地数据
    /// </summary>
    /// <returns></returns>
    public LightDataHelper LoadDate(string file)
    {
        if (!Directory.Exists(path))
        {
            return null;
        }
        string fileName = Path.Combine(path, file);
        if (!File.Exists(fileName))
        {
            return null;
        }
        //从文件里面读取数据
        string json = File.ReadAllText(fileName, Encoding.UTF8);
        instances = JsonUtility.FromJson<LightDataHelper>(json);
        return instances;
    }
}
